<?php
namespace Home\Controller;
use Think\Controller;
header("Content-type: text/html; charset=utf-8");
class SearchController extends CommonController {
  // public function _initialize(){
  //     //判断用户是否已经登录
  //     if (!isset($_SESSION['uid'])) {
  //         $this->error('对不起,您还没有登录!请先登录再进行浏览', U('Login/login'), 1);
  //     }
  // }
  //太阳高效搜索,搜索控制器,搜索后跳转到搜索主页
    public function index(){
    check_ad_time();
    $cate =D('cate'); //读取分类总表
    $users =D('users');
    $id=(int) session('uid');
    $usersvip=$users->field('userid,vip')->where(array('userid'=>$id))->select();//用户级别查找
    $this->assign('usersvip',$usersvip);// 赋值超链数据集
    $cates=$cate->where('id=240')->find();
    $catesons=$cate->where('pid='.$cates['id'])->select(); //获取子分类和其id
    $where=array('pid'=>0); //只显示顶级分类
    $navres=$cate->field('id,name,type')->order('sort asc')->where($where)->select();
    $this->assign('navres',$navres);        //顶部 顶级分类
    if($cates['pid']==0 && !$catesons){
      $cates=$cate->where('id=240')->find();
    }
    $catesons=$cate->field('id,name,is_grail')->where('pid='.$cates['id'])->select();//只取id 和name字段
    //if($kw=I('kws')){ // 2.获取关键字$kw   kw不为空
    //}
  $kw = I('kws');
  if(empty($kw)){
    $this->error('关键词不能为空！');
  }

  /*记录登录用户的搜索记录yj*/
  if (session('uid')>0) {
    /*查询用户是否搜索过这个关键词*/
    $search_con = array('user_id'=>session('uid'),'key_words'=>$kw);
    $is_seached = M("user_search_rec")->where($search_con)->count();
    /*如果搜索过，就让那个记录的次数加1,刷新上次更新时间*/
    if ($is_seached) {
      $last_update = time();
      $data = array('last_update'=>$last_update);
      M("user_search_rec")->where($search_con)->setInc('times',1);
      M("user_search_rec")->where($search_con)->save($data);
    }else{
      /*否则就增加一条记录*/
      $rec_data = array(
          'user_id'=>session('uid'),
          'key_words'=>$kw,
          'times'=>'1',
          'add_time'=>time(),
          'last_update'=>time()
        );
      M('user_search_rec')->add($rec_data);
    }

    //获取用户自定义模块 yj
    $user_block = M('user_block')->where(array('user_id'=>session('uid')))->select();
    $this->assign('user_block',$user_block);
  }
  $logined = $id > 0 ? 1 : 0;
  $this->assign('logined',$logined);

  //获取全站搜索热词 yj
  $site_hot_word = M('user_search_rec')->where(array('user_id'=>session('uid')))->order('last_update desc')->limit(12)->select();
  $this->assign('site_hot_word',$site_hot_word);
  
  //lkl新增，判断我的收藏和添加类型
    $type = I('type');
    $ret = array();  //用[]系统报错 5.3版识别不出来
    foreach ($catesons as $k=>$v) {
      if($v['name']==$kw)
      {
        $ret['']=$v['id'];
      }
    }
    //获取二级分类下的超链
    $ret['cateid']= array('eq',$ret['']); //用$ret['']
    $yj_cateid = $ret['cateid'];
    /*获取当前关键字下收藏数据start*/
    $sid_arr_org = M('user_collection')->field('slink_id')->where(array('user_id'=>session('uid')))->select();
    $id_str = '';
    foreach ($sid_arr_org as $k => $v) {
      $id_str .= $v['slink_id'];
      if ($k < count($sid_arr_org)-1) {
        $id_str .= ','; //获取我的收藏id，排序拼凑
      }
    }
    $slink=D('slink'); //1.先实例化slink表，获得数据
    $condition = '';
    $condition['id'] = array('in',$id_str);
    $condition['cateid'] = $yj_cateid;
    $col_list  = $slink->where($condition)->where("atype=0")->select();//我的收藏列表。
    $col_count = count($col_list);//我的收藏数量
    $this->assign('col_list',$col_list);
    $this->assign('col_count',$col_count);
    /*获取当前关键字下收藏数据end*/

    /*用户添加过的数据start*/
    $condition = '';
    $user_id = session('uid');
    $username = M('users')->where(array('userid'=>$user_id))->field('username')->find();
    $condition['author'] = $username['username'];
    $condition['cateid'] = $yj_cateid;
    $add_list  = $slink->where($condition)->where("atype=0")->select();
    $add_count = count($add_list);
    $this->assign('add_list',$add_list);
    $this->assign('add_count',$add_count);
    /*用户添加过的数据end*/

    //lkl统一条件
    $listaswhehr = ' atype=0 ';
    if($user_id>0){
      if($type == 'my_col'){
        $listaswhehr .= " AND id in($id_str) " ;
      }elseif($type == 'my_add'){
        $listaswhehr .= " AND author ='$username[username]' ";
      }
    }
    //$count = $slink->where($ret)->count();// 查询满足要求的总记录数
    $count = $slink->where($ret)->where($listaswhehr)->count();// 查询满足要求的总记录数
    //总收藏数
    $col_sum = $slink->where($ret)->sum('col_count');
    $this->assign('col_sum',$col_sum);
    //收藏数
    $my_col_con = $ret;
    $my_colcon['author'] = $username['username'];
    $my_col_sum = $slink->where($ret)->sum('col_count');
    $this->assign('my_col_sum',$my_col_sum);

    //用户排名数据
    $crt_rank = 0;
    $temp_pos = 0;

    $yj_user_rank = $this->yj_user_rank($ret);
    $user_rank_list = array();
    foreach ($yj_user_rank['list'] as $k => $v) {
      $pos++;
      $yj_user_rank['list'][$k]['rate'] = round($v['count'] / $yj_user_rank['sum'],2)*100;
      if ($v['author'] == $username['username']) {
        $crt_rank = $pos;
      }
    }

    //dump($yj_user_rank);exit;

    $total_add = count($yj_user_rank['list']);
    //承包的学校
    $this->assign('top_school',$yj_user_rank['top_school']);
    $this->assign('total_add',$total_add);
    $this->assign('user_rank',$yj_user_rank['list']);
    $this->assign('crt_rank',$crt_rank);

    $page = new \Think\Page($count,24);   // 实例化分页类 传入总记录数和每页显示的记录数(25)
    //排序
    $listas = $slink->where($ret)->where($listaswhehr)->order("sort DESC,col_count DESC")->limit($page->firstRow.','.$page->listRows)->select();
    foreach ($listas as $k => $v) {
      $near_list = $this->get_near_list($v['link'],$v['id']);
      $listas[$k]['near_list'] = $near_list['list'];
      $listas[$k]['near_count'] = $near_list['count'];
    }

    /*获取当前关键字下的添加数据*/
    $listasi = $slink->where($ret)->where("atype=1")->limit($page->firstRow.','.$page->listRows)->select();
    $listasc = $slink->where($ret)->where("atype=2")->limit($page->firstRow.','.$page->listRows)->select();
     $listass = $slink->where($ret)->where("atype=3")->limit($page->firstRow.','.$page->listRows)->select();
    $show= $page->show();// 分页显示输出
    //Tags标签数组
    $tagsArr=$this->getTags();
    //同链词语
    $userinfos = M('users')->where(array('userid'=>session('uid')))->find();
    $this->assign('userinfo',$userinfos);
    $this->assign('page',$show);// 赋值分页输出
    $this->assign('listas',$listas);// 赋值超链数据集
    $this->assign('listasi',$listasi);// 赋值超链数据集
    $this->assign('listasc',$listasc);// 赋值超链数据集
    $this->assign('listass',$listass);// 赋值超链数据集
    //dump($listas);
    $this->assign('catesons',$catesons);
    $cateaddoid=$cate->field('id')->where('pid=0')->select();
    $this->assign('cateaddoid',$cateaddoid);// 赋值超链数据集
    $this->assign('tagsArr',$tagsArr); //标签
    $this->assign('ret',$ret); //标签
    $this->assign('kw',$kw);  //把值赋给前台模板
    //lkl新增，底部广告
  $Ad = D('s_ad');
  $now = time();
  $ad_list = $Ad->where(" cat_name='$kw' AND type = 2 AND end_time >= $now")->select();
  $file="./App/Common/Conf/config.php"; //全局配置
  $config = include $file;
  $last_at_list = array();
  for($i=1;$i<=$config['ad_num'];$i++){
    $last_at_list[$i] = '';
    foreach($ad_list as $k=>$v){
      $uinfo = D('users')->field('username')->where("userid=$v[uid]")->find();
      $v['uname'] = $uinfo['username'];
      $v['is_tousu'] = 0;
      //用户投诉状态
      $is_tousu = D('complain_log')->where(" uid='$user_id' AND aid = $v[ad_id] AND status = 1 ")->find();
      if(!empty($is_tousu)){
        $v['is_tousu'] = 1;
        $v['tousu_n'] = '取消投诉';
      }else{
        $v['tousu_n'] = '投诉';
      }
      if($v['position'] == $i){
        $last_at_list[$i] = $v;
      }
    }
  }
  $this->assign('last_at_list',$last_at_list);  //把值赋给前台模板
  /* $this->assign('is_max',$is_max);  //把值赋给前台模板 */
  
  $this->display();
  }
  //添加超链，默认类型为0
  public function addone(){
   if(IS_POST){
            //放在post里
            $slink=D('slink'); //1.先实例化cate表，获得数据,不可少
            $data['title']    = I('title');
            $data['trait']    = I('trait');
            $data['link']     = I('link');
            $data['cateid']   = I('cateidurl');
            $upload = new \Think\Upload();// 先实例化上传类
            $upload->maxSize   = 3145728 ;// 设置附件上传大小
            $upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath  = './slink/'; // 设置附件上传目录
            $upload->rootPath  = './Upload/';
            // 上传文件
            $info   =   $upload->upload();
            $data['tags']     =I('tags');
            $data['tags2']    =I('tags2');
            $data['tags3']    =I('tags3');
            $data['tags4']    =I('tags4');
            $data['tags5']    =I('tags5');
            $data['tags6']    =I('tags6');
            $data['tags7']    =I('tags7');
            $data['tags8']    =I('tags8');
            $data['tags9']    =I('tags9');
            $data['tags10']   =I('tags10');
            $data['author']   =$_SESSION['username'];
            $data['userid']   =$_SESSION['userid']; //添加者id
            $lu =date("Y-m-d");
            $data['img']="$lu/".$info['img']['savename'];
            $data['content'] =I('content');
            //$data['verify']  =I('verify');
            /*加积分*/
            /*判断数量*/
            $data['time']=time();
            $data['create_time'] = NOW_TIME;
      if($slink->create($data)){
            if($slink->add()){
                 $this->success('添加成功！');
            }else{
                $this->error('提交失败！');
            }
        }else{
            $this->error($slink->getError());
        }
        return;
        }
        $this->display();
  }
  //添加超链，默认类型为0
  public function add(){
   if(IS_POST){
    /*用户数据*/
      $userinfo=D('users');
      $where=array('userid'=>session('uid'));
      $userinfos=$userinfo->where($where)->find();
      $user_id = session('uid');
      $vip_key = '';
      $file="./App/Common/Conf/config.php"; //全局配置
      $word_times = 0;
      $config = include $file;
      $now = strtotime(date("Y-m-d"));
      /*过期初始化*/
      if ($userinfos['link_time'] < $now) {
        $res = M()->execute(" update users set link_add = 0, link_time = '$now' where userid = '$user_id'");
      }
      /*次数限制*/
      if ($userinfos['vip'] > 0) {
        $vip_key .='LINK_VIP'.$userinfos['vip'];
        $word_times = $config[$vip_key];
        if ($userinfos['link_add'] >= $word_times) {
          $this->error('超出次数限制');
        }
      }
      //放在post里
      $slink=D('slink'); //1.先实例化cate表，获得数据,不可少
      $data['title']    = I('title');
      $data['trait']    = I('trait');
      $data['link']     = I('link');
      $data['cateid']   = I('cateidurl');
      $upload = new \Think\Upload();// 先实例化上传类
      $upload->maxSize   = 3145728 ;// 设置附件上传大小
      $upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->savePath  = './slink/'; // 设置附件上传目录
      $upload->rootPath  = './Upload/';
      // 上传文件
      $info   =   $upload->upload();
      $data['tags']     =I('tags');
      $data['tags2']    =I('tags2');
      $data['tags3']    =I('tags3');
      $data['tags4']    =I('tags4');
      $data['tags5']    =I('tags5');
      $data['tags6']    =I('tags6');
      $data['tags7']    =I('tags7');
      $data['tags8']    =I('tags8');
      $data['tags9']    =I('tags9');
      $data['tags10']   =I('tags10');
      $data['author']   =$_SESSION['username'];
      $data['userid']   =$_SESSION['userid']; //添加者id
      $lu =date("Y-m-d");
      $data['img']="$lu/".$info['img']['savename'];
      $data['content'] =I('content');
      $data['time']=time();
      $data['create_time'] = NOW_TIME;
      if($slink->create($data)){
        if($slink->add()){
          /*积分增加*/
          $score = $config['ADD_LINK'];
          M()->execute(" update users set integral = (integral + '$score') where userid = '$user_id'");
          /*记录log*/
        $log_data = array(
          'user_id'=>$user_id,
          'integral'=>$score,
          'desc'=>'添加链接',
          'add_time'=>time()
        );
        M('integral_log')->add($log_data);
        M()->execute(" update users set link_add = (link_add + '$score') where userid = '$user_id'");
            $this->success('添加成功！');
          }else{
            $this->error('提交失败！');
          }
      }else{
            $this->error($slink->getError());
        }
        return;
    }
    $this->display();
  }
  //添加搜索词
  public function addo(){
    if(IS_POST){
      /*用户数据*/
      $userinfo=D('users');
      $where=array('userid'=>session('uid'));
      $userinfos=$userinfo->where($where)->find();
      $user_id = session('uid');
      $vip_key = '';
      $file="./App/Common/Conf/config.php"; //全局配置
      $word_times = 0;
      $config = include $file;
      $now = strtotime(date("Y-m-d"));
      /*过期初始化*/
      if ($userinfos['word_time'] < $now) {
        M()->execute(" update users set word_add = 0, word_time = '$now' where userid = '$user_id'");
      }
      /*次数限制*/
      if ($userinfos['vip'] > 0) {
        $vip_key .='WORD_VIP'.$userinfos['vip'];
        $word_times = $config[$vip_key];
        if ($userinfos['word_add'] >= $word_times) {
          $this->error('超出次数限制');
        }
      }
      //放在post里
      $cate=D('cate'); //1.先实例化cate表，获得数据,不可少
      $data['name']    = I('name');
      $data['pid']    = I('path.2');
      $data['userid']    = session('uid');
      if($cate->create($data)){
          if($cate->add()){
            /*积分增加*/
            $score = $config['ADD_WORD'];
            M()->execute(" update users set integral = (integral + '$score') where userid = '$user_id'");
            M()->execute(" update users set word_add = (word_add + '$score') where userid = '$user_id'");
            /*记录日志*/
            $log_data = array(
              'user_id'=>$user_id,
              'integral'=>$score,
              'desc'=>'增加关键词',
              'add_time'=>time()
            );
            M('integral_log')->add($log_data);
            $this->success('添加成功！');
          }else{
            $this->error('提交失败！');
          }
        }else{
          $this->error($cate->getError());
        }
      return;
    }
    $this->display();
  }
  //添加右侧相关搜索，类型为2
  public function addc(){
    if(IS_POST){
      //放在post里
      $slink=D('slink'); //1.先实例化cate表，获得数据,不可少
      $data['title']    = I('title');
      $data['trait']     = I('trait');
      $data['link']     = I('link');
      $data['cateid']   = I('cateidurl');
      $data['atype']     = I('atype');//超链类型
      $upload = new \Think\Upload();// 先实例化上传类
      $upload->maxSize   = 3145728 ;// 设置附件上传大小
      $upload->exts      = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->savePath  = './slink/'; // 设置附件上传目录
      $upload->rootPath  = './Upload/';
      // 上传文件
      $info   =   $upload->upload();
      $data['author']   =$_SESSION['username'];
      $lu =date("Y-m-d");
      $data['img']="$lu/".$info['img']['savename'];
      $data['content'] =I('content');
      $data['time']=time();
      $data['create_time'] = NOW_TIME;
      if($slink->create($data)){
        if($slink->add()){
          $this->success('添加成功！');
        }else{
          $this->error('提交失败！');
        }
      }else{
        $this->error($slink->getError());
      }
      return;
    }
    $this->display();
  }
  //添加下边相关搜索词 类型为1  vip2以上开放使用
  public function addi(){
    if(IS_POST){
      $slink=D('slink'); //1.先实例化cate表，获得数据,不可少
      $data['title']    = I('title');
      $data['atype']     = I('atype');//超链类型
      $data['link']     = I('link');
      $data['cateid']   = I('cateidurl');
      $data['author']   =$_SESSION['username'];
      $data['time']=time();
      $data['create_time'] = NOW_TIME;
      if($slink->create($data)){
        if($slink->add()){
          $this->success('添加成功！');
        }else{
          $this->error('提交失败！');
        }
      }else{
        $this->error($slink->getError());
      }
      return;
    }
    $this->display();
  }
    //添加下边相关本站搜索词 类型为1  vip2以上开放使用
  public function adds(){
    if(IS_POST){
      $slink=D('slink'); //1.先实例化cate表，获得数据,不可少
      $data['title']    = I('title');
      $data['atype']     = I('atype');//超链类型
      $data['link']     = I('link');
      $data['cateid']   = I('cateidurl');
      $data['author']   =$_SESSION['username'];
      $data['time']=time();
      $data['create_time'] = NOW_TIME;
      if($slink->create($data)){
        if($slink->add()){
          $this->success('添加成功！');
        }else{
          $this->error('提交失败！');
        }
      }else{
        $this->error($slink->getError());
      }
      return;
    }
    $this->display();
  }
  public function getTags(){
      $tags=C('tags');
      $tagsArr=explode(',', $tags); //explode 数组打散为字符串
      return $tagsArr;
  }
  //编辑搜索栏
  public function edite(){
  }
  //更新搜索栏
  public function updata(){
  }
  //删除搜索栏
  public function del(){
  }
  //用户退出
  public function loginOut(){
    //卸载session
    session_unset();
    //销毁session
    session_destroy();
    //删除用于自动登录的cookie
    @setcookie("auto",'',time() - 3600,'/');
    $this->redirect('Index/index');
  }
  /*ajax 超链收藏  kw*/
  public function col(){
    $sid = !empty($_POST['sid'])? $_POST['sid'] : 0;
    $user_id = session('uid');
    $collection = M('user_collection');
    /*搜索用户是否收藏*/
    $count = $collection->where(array('user_id'=>$user_id,'slink_id'=>$sid))->count();
    if ($count > 0) {
      die('0');
      exit;
    }
    $data= array(
      'user_id'=>$user_id,
      'slink_id'=>$sid,
      'add_time'=>time()
      );
    $collection->add($data);
    M()->execute(" update slink set col_count = (col_count + 1) where id = '$sid'");
    die('1');
  }
  /*ajax 添加*/
  public function yj_add(){
    $sid = !empty($_POST['sid'])? $_POST['sid'] : 0;
    $user_id = session('uid');
    $addition = M('user_add');
    /*搜索用户是否添加*/
    $count = $addition->where(array('user_id'=>$user_id,'slink_id'=>$sid))->count();
    if ($count > 0) {
      die('0');
      exit;
    }
    $data= array(
      'user_id'=>$user_id,
      'slink_id'=>$sid,
      'add_time'=>time()
      );
    $addition->add($data);
    $res = M()->execute(" update slink set col_count = (col_count + 1) where id = '$sid'");
    die($res);
  }
  /*我的收藏显示*/
  public function my_collection(){
    $cate =D('cate'); //读取分类总表
    $users =D('users');
    $id=(int) session('uid');
    $usersvip=$users->field('userid,vip')->where(array('userid'=>$id))->select();//用户级别查找
    $this->assign('usersvip',$usersvip);// 赋值超链数据集
    $cates=$cate->where('id=240')->find();
    $catesons=$cate->where('pid='.$cates['id'])->select(); //获取子分类和其id
    $where=array('pid'=>0); //只显示顶级分类
    $navres=$cate->field('id,name,type')->order('sort asc')->where($where)->select();
    $this->assign('navres',$navres);//顶部 顶级分类
    if($cates['pid']==0 && !$catesons){
      $cates=$cate->where('id=240')->find();
    }
    $catesons=$cate->field('id,name,is_grail')->where('pid='.$cates['id'])->select();//只取id 和name字段
    if($kw=I('kws')){ // 2.获取关键字$kw   kw不为空
      //var_dump($kw);exit;
    }
    $ret = array();  //用[]系统报错 5.3版识别不出来
    foreach ($catesons as $k=>$v) {
        if($v['name']==$kw)
        {
            $ret['']=$v['id'];
        }
    }
    //获取二级分类下的超链
    $ret['cateid'] = array('eq',$ret['']); //用$ret['']
    $yj_cateid = $ret['cateid'];
    $slink=D('slink'); //1.先实例化slink表，获得数据
    $count=$slink->where($ret)->count();// 查询满足要求的总记录数
    $page=new \Think\Page($count,24);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    /*用户收藏过的数据id*/
    $sid_arr_org = M('user_collection')->field('slink_id')->where(array('user_id'=>session('uid')))->select();
    $id_str = '';
    foreach ($sid_arr_org as $k => $v) {
      $id_str .= $v['slink_id'];
      if ($k < count($sid_arr_org)-1) {
        $id_str .= ',';
      }
    }
    $condition['id'] = array('in',$id_str);
    $listas  = $slink->where($condition)->where("atype=0")->limit($page->firstRow.','.$page->listRows)->select();
    foreach ($listas as $k => $v) {
      if ($v['cateid'] == $yj_cateid) {
        unset($listas[$k]);
      }
    }
    // echo "<pre>";
    // print_r($listas);
    // print_r($ret);
    // echo "</pre>";
    // exit;
    $this->assign('res_count',count($listas));
    $listasi = $slink->where($ret)->where("atype=1")->limit($page->firstRow.','.$page->listRows)->select();
    $listasc = $slink->where($ret)->where("atype=2")->limit($page->firstRow.','.$page->listRows)->select();
    $show= $page->show();// 分页显示输出
    //Tags标签数组
    $tagsArr=$this->getTags();
    $this->assign('page',$show);// 赋值分页输出
    $this->assign('listas',$listas);// 赋值超链数据集
    $this->assign('listasi',$listasi);// 赋值超链数据集
    $this->assign('listasc',$listasc);// 赋值超链数据集
    $this->assign('catesons',$catesons);
    $cateaddoid=$cate->field('id')->where('pid=0')->select();
    $this->assign('cateaddoid',$cateaddoid);// 赋值超链数据集
    $this->assign('tagsArr',$tagsArr); //标签
    $this->assign('ret',$ret); //标签
    $this->assign('kw',$kw);  //把值赋给前台模板
    $this->display();
  }
  /*我的添加显示*/
  public function my_add(){
    $cate =D('cate'); //读取分类总表
    $users =D('users');
    $id=(int) session('uid');
    $usersvip=$users->field('userid,vip')->where(array('userid'=>$id))->select();//用户级别查找
    $this->assign('usersvip',$usersvip);// 赋值超链数据集
    $cates=$cate->where('id=240')->find();
    $catesons=$cate->where('pid='.$cates['id'])->select(); //获取子分类和其id
    $where=array('pid'=>0); //只显示顶级分类
    $navres=$cate->field('id,name,type')->order('sort asc')->where($where)->select();
    $this->assign('navres',$navres);//顶部 顶级分类
    if($cates['pid']==0 && !$catesons){
       $cates=$cate->where('id=240')->find();
    }
    $catesons=$cate->field('id,name,is_grail')->where('pid='.$cates['id'])->select();//只取id 和name字段
    if($kw=I('kws')){ // 2.获取关键字$kw   kw不为空
    }
    $ret = array();  //用[]系统报错 5.3版识别不出来
    foreach ($catesons as $k=>$v) {
      if($v['name']==$kw)
      {
          $ret['']=$v['id'];
      }
    }
    //获取二级分类下的超链
    $ret['cateid']= array('eq',$ret['']); //用$ret['']
    $yj_cateid = $ret['cateid'];
    $slink=D('slink'); //1.先实例化slink表，获得数据
    $count=$slink->where($ret)->count();// 查询满足要求的总记录数
    $page=new \Think\Page($count,24);// 实例化分页类 传入总记录数和每页显示的记录数(25)
    //$condition['id'] = array('in',$id_str);
    $user_id = session('uid');
    $username = M('users')->where(array('userid'=>$user_id))->field('username')->find();
    $listas  = $slink->where(array('author'=>$username['username']))->where("atype=0")->limit($page->firstRow.','.$page->listRows)->select();
    // echo "<pre>";
    // print_r($listas);
    // print_r($yj_cateid);
    // echo "</pre>";
    // exit;
    foreach ($listas as $k => $v) {
      if ($v['cateid'] != $yj_cateid) {
        unset($listas[$k]);
      }
    }
    $listasi = $slink->where($ret)->where("atype=1")->limit($page->firstRow.','.$page->listRows)->select();
    $listasc = $slink->where($ret)->where("atype=2")->limit($page->firstRow.','.$page->listRows)->select();
    $show= $page->show();// 分页显示输出
    //Tags标签数组
    $tagsArr=$this->getTags();
    $this->assign('page',$show);// 赋值分页输出
    $this->assign('listas',$listas);// 赋值超链数据集
    $this->assign('listasi',$listasi);// 赋值超链数据集
    $this->assign('listasc',$listasc);// 赋值超链数据集
    $this->assign('catesons',$catesons);
    $cateaddoid=$cate->field('id')->where('pid=0')->select();
    $this->assign('cateaddoid',$cateaddoid);// 赋值超链数据集
    $this->assign('tagsArr',$tagsArr); //标签
    $this->assign('ret',$ret); //标签
    $this->assign('kw',$kw);  //把值赋给前台模板
    $this->display();
  }
  /*取消收藏*/
  public function de_col(){
    $sid = !empty($_POST['sid'])? $_POST['sid'] : 0;
    $user_id = session('uid');
    $addition = M('user_collection');
    $count = $addition->where(array('user_id'=>$user_id,'slink_id'=>$sid))->count();
    if ($count) {
      $res = $addition->where(array('user_id'=>$user_id,'slink_id'=>$sid))->delete();
      M()->execute(" update slink set col_count = (col_count - 1) where id = '$sid'");
    }
    if ($res) {
      die('1');
    }else{
      die('0');
    }
  }
  /*取消添加*/
  /*
  public function my_de_add(){
    $sid = !empty($_POST['sid'])? $_POST['sid'] : 0;
    $user_id = session('uid');
    $addition = M('user_add');
    $count = $addition->where(array('user_id'=>$user_id,'slink_id'=>$sid))->count();
    if ($count) {
      $res = $addition->where(array('user_id'=>$user_id,'slink_id'=>$sid))->delete();
    }
    if ($res) {
      die('1');
    }else{
      die('0');
    }
  }*/


  /*搜索页用户自定义模块相关操作 start yjmp*/
  /**
   * 用户添加模块
   */
  public function add_block(){
    //获取数据
    $user_id = session('uid');
    $block_name = $_POST['block_name'];
    $result = array(
      'err'=>'0',
      'block_id'=>'0',
      'msg'=>''
    );

    //验证
    if (!$user_id) {
      $result['err'] = '1';
      $result['msg'] = '请登录后重试';
      die(json_encode($result));
    }

    if (!$block_name) {
      $result['err'] = '1';
      $result['msg'] = '模块名称不合法';
      die(json_encode($result));
    }

    //写入数据库
    $data = array(
      'user_id'=>$user_id,
      'block_title'=>$block_name,
      'add_time'=>time(),
      'last_update'=>time()
    );
    $block_id = M('user_block')->add($data);
    if ($block_id) {
        $result['block_id'] = $block_id;
        $result['msg'] = '添加成功';
    }else{
      $result['err'] = '1';
      $result['msg'] = '添加失败';
    }
    die(json_encode($result));
  }

  /**
   * tab切换
   */
  public function change_tab(){
    $block_id = $_POST['block_id'];
    $user_id = session('uid');
    $result = array(
      'err'=>'0',
      'msg'=>'',
      'content'=>''
    );
    if (!$block_id) {
      $result['err'] = '1';
      $result['msg'] = '非法入口';
      die(json_encode($result));
    }
    
    $result['ele_id'] = $block_id;
    $result['editable'] = 0;

    switch ($block_id) {
      //全站热词
      case 'usual':
        $result['content'] = M('user_search_rec')->order('times desc')->limit(10)->select();
        foreach ($result['content'] as $k => $v) {
          $result['content'][$k]['yj_url'] = '?kws='.$v['key_words'];
          $result['content'][$k]['name'] = $v['key_words'];
        }
        break;
      //用户搜索排行热词
      case 'recent':
        if ($user_id) {
          $result['content'] = M('user_search_rec')->where(array('user_id'=>$user_id))->order('last_update desc')->limit(12)->select();
          foreach ($result['content'] as $k => $v) {
            $result['content'][$k]['yj_url'] = '?kws='.$v['key_words'];
            $result['content'][$k]['name'] = $v['key_words'];
          }
        }else{
          $result['err'] = '1';
          $result['msg'] = '请登录后重试';
        }
        break;
      //用户自定义模块
      default:
        $block_id_t = substr($block_id, 4);
        $result['content'] = M('block_word')->where(array('user_id'=>$user_id,'block_id'=>$block_id_t))->select();
        $result['editable'] = 1;
        foreach ($result['content'] as $k => $v) {
          //判断用户的链接有没有http
          $prifix = substr($v['word_url'], 0,4);
          if ($prifix == 'http') {
            $result['content'][$k]['yj_url'] = $v['word_url'];
          }else{
            $result['content'][$k]['yj_url'] = '?kws='.$v['word_url'];
          }
          
          $result['content'][$k]['name'] = $v['word_title'];
        }
        break;
    }
    die(json_encode($result));
  }

  /**
   * 用户模块编辑
   */
  public function edit_block(){
    $block_id = $_POST['block_id'];
    $block_name = $_POST['block_name'];
    $is_exist = M('user_block')->where(array('block_id'=>$block_id))->count();
    $result = array(
      'err'=>0,
      'msg'=>''
    );

    if (!$is_exist) {
      $result['err'] = 1;
      $result['msg'] = '模块不存在';
      die(json_encode($result));
    }

    $data = array(
        'block_title'=>$block_name,
        'last_update'=>time()
      );
      $res = M('user_block')->where(array('block_id'=>$block_id))->save($data);
      if (!$res) {
        $result['err'] = 1;
       $result['msg'] = '更新失败';
      }
    die(json_encode($result));
  }

  /**
   * 用户模块删除
   */
  public function del_block(){
    $block_id = $_POST['block_id'];
    $result = array(
      'err'=>0,
      'msg'=>''
    );
    $is_exist = M('block_word')->where(array('block_id'=>$block_id))->count();

    if ($is_exist) {
      $result['err'] = 1;
      $result['msg'] = '请先删除该模块下热词';
      die(json_encode($result));
    }

    M('user_block')->where(array('block_id'=>$block_id))->delete();
    M('block_word')->where(array('block_id'=>$block_id))->delete();
    die(json_encode($result));
  }

  /**
   * 添加热词
   */
  public function add_hot_word(){
    $user_id = session('uid');
    $site_name = trim($_POST['site_name']);
    $site_url = trim($_POST['site_url']);
    $block_id = trim($_POST['block_id']);
    $block_id = substr($block_id, 4);
    $add_time = time();
    $result = array(
      'err'=>'0',
      'msg'=>'',
      'word_id'=>''
    );

    if (!$user_id) {
      $result['err'] = '1';
      $result['msg'] = '登录后重试';
      die(json_encode($result));
    }

    //如果用户没有填写链接用搜索名称
    if ($word_url == '') {
      $word_url = $site_name;
    }

    $data = array(
      'block_id'=>$block_id,
      'user_id'=>$user_id,
      'word_title'=>$site_name,
      'word_url'=>$site_url,
      'add_time'=>$add_time,
      'last_update'=>$add_time
    );

    $res = M('block_word')->add($data);
    $prifix = substr($site_url, 0,4);

    if (!$res) {
      $result['err'] = '1';
      $result['msg'] = '未知错误，重试'; 
    }else{
      $result['word_id'] = $res;
    }
    die(json_encode($result));
  }

  /**
   * 编辑热词
   */
  public function edit_hot_word(){
    $user_id = session('uid');
    $site_name = trim($_POST['site_name']);
    $site_url = trim($_POST['site_url']);
    $word_id = trim($_POST['word_id']);
    $add_time = time();
    $result = array(
      'err'=>'0',
      'msg'=>''
    );
    if (!$user_id) {
      $result['err'] = '1';
      $result['msg'] = '登录后重试';
      die(json_encode($result));
    }

    $data = array(
      'word_title'=>$site_name,
      'word_url'=>$site_url,
      'last_update'=>$add_time
    );

    $res = M('block_word')->where(array('word_id'=>$word_id))->save($data);

     $prifix = substr($site_url, 0,4);
    if ($prifix != 'http') {
      $site_url = '?kws='.$site_url;
    }

    if (!$res) {
      $result['err'] = '1';
      $result['msg'] = '该内容已存在';
    }
    die(json_encode($result));
  }

  /**
   * 删除热词
   */
  public function del_hot_word(){
    $word_id = trim($_POST['word_id']);
    $result = array('err'=>0,'msg'=>'');
    $res = M('block_word')->where(array('word_id'=>$word_id))->delete(); 
    if (!$res) {
      $result['err'] = '1';
      $result['msg'] = '删除失败，请重试';
    }
    die(json_encode($result));
  }
  /*搜索页用户自定义模块相关操作 end yjmp*/

  /**
   * 某类关键词下用户添加排行
   * @param  [type] $where 条件
   */
  public function yj_user_rank($where){
    $res = M('slink')->distinct(true)->field('author')->where($where)->select();
    $rank_arr = array();
    $pos = 0;
    $sum_count = 0;
    foreach ($res as $k => $v) {
      if ($v['author'] != '') {
        $where['author'] = array('eq',$v['author']);
        $count = M('slink')->where($where)->sum('col_count');
        $rank_arr[$pos]['author'] = $v['author'];
        $rank_arr[$pos]['count'] = $count;
        $sum_count += $count;
        $pos++;
      }
    }
    $result['list'] = $this->array_sort($rank_arr,'count',SORT_DESC);
    //承包的大学
    $top_author = M('users')->where(array('username'=>$result['list'][0]['author']))->find();
    $result['top_school'] = $top_author['school'];
    $result['sum'] = $sum_count;
    return $result;
  }

  /**
   * 获取相同链接的类似词
   * @param  [type] $link [description]
   * @param  [type] $id   [description]
   */
  public function get_near_list($link,$id){
    $Model = new \Think\Model();
    $near_list = array();
    $res = $Model->query("select * from slink where link = '$link' and id<>'$id' order by RAND() limit 9");
    $near_list['list'] = $res;
    $count = M('slink')->where(array('link'=>$link))->count();
    $near_list['count'] = $count - 1;
    return $near_list;
  }

  /**
   * 二维数组按key排序
   * @param  [type] $array 数组
   * @param  [type] $on    排序条件
   * @param  [type] $order 顺序
   */
  public function array_sort($array, $on, $order=SORT_ASC)
  {
      $new_array = array();
      $sortable_array = array();

      if (count($array) > 0) {
          foreach ($array as $k => $v) {
              if (is_array($v)) {
                  foreach ($v as $k2 => $v2) {
                      if ($k2 == $on) {
                          $sortable_array[$k] = $v2;
                      }
                  }
              } else {
                  $sortable_array[$k] = $v;
              }
          }

          switch ($order) {
              case SORT_ASC:
                  asort($sortable_array);
              break;
              case SORT_DESC:
                  arsort($sortable_array);
              break;
          }

          foreach ($sortable_array as $k => $v) {
              $new_array[$k] = $array[$k];
          }
      }

      return $new_array;
  }

  /**
   * 前台刷新就类似链接
   */ 
  public function refresh_near_list(){
    $link_id = $_POST['link_id'];
    $slink = M('slink')->where(array('id'=>$link_id))->find();
    $result = array(
      'err'=>0,
      'msg'=>'',
      'content'=>''
    );
    if (!$slink) {
      $result['err'] = '1';
      $result['msg'] = '错误！没有其他词了';
    }

    $link = $slink['link'];
    $nearlist = $this->get_near_list($link,$link_id);
    $result['content'] = $nearlist['list'];
    die(json_encode($result));
  }
}